package com.dinadi.yidi.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.bean.ExhibitionRegistrationBean;
import com.dinadi.yidi.bean.OrderDetailsBean;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.http.interfaces.IntegralChangeInterface;
import com.dinadi.yidi.utils.FormatCurrentData;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.StringUtil;
import com.dinadi.yidi.utils.ToastUtil;
import com.dinadi.yidi.utils.UtilPopupWindow;
import com.pingplusplus.android.Pingpp;
import com.dinadi.yidi.utils.UtilPopupWindow;

/**
 * author: JiaYu.He
 * Date: 2017/6/26   填写报名信息
 * Time: 17:05
 */
public class RegistrationInformationActivity extends BaseActivity {
    private View view;
    private TextView tvTitle;
    private TextView time, place, cost, competition_title;
    private ImageView btn_confirm_enrollment;
    private EditText edit_competition_user, edit_competition_phone;
    private String user, phone;
    private String userID, token;
    /*展赛ID*/
    private String showId, showUserLogId;
    private String id,status;

    @Override
    protected View getLayout() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        view = LayoutInflater.from(RegistrationInformationActivity.this).inflate(R.layout.activity_registration_information, null);
        return view;
    }

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected void initView() {
        changePager(2);
        tvTitle = (TextView) view.findViewById(R.id.text_title);
        tvTitle.setText(getResources().getString(R.string.text_registration_information));
        time = (TextView) view.findViewById(R.id.time);
        place = (TextView) view.findViewById(R.id.place);
        cost = (TextView) view.findViewById(R.id.cost);
        competition_title = (TextView) view.findViewById(R.id.title);
        btn_confirm_enrollment = (ImageView) view.findViewById(R.id.btn_confirm_enrollment);
        edit_competition_user = (EditText) view.findViewById(R.id.edit_competition_user);
        edit_competition_phone = (EditText) view.findViewById(R.id.edit_competition_phone);
    }

    @Override
    protected void initListener() {
        registerClickListener(btn_confirm_enrollment);
    }

    @Override
    public void onResume() {
        super.onResume();
        String isRefresh = SharePreferencesHelper.getInstance(this).getString("isRefresh");
        if ("yes".equals(isRefresh)) {
            userID = SharePreferencesHelper.getInstance(this).getString("userId");
            token = SharePreferencesHelper.getInstance(this).getString("token");
            SharePreferencesHelper.getInstance(this).putString("isRefresh", "no");
        }
    }

    @Override
    protected void initData() {
        userID = SharePreferencesHelper.getInstance(RegistrationInformationActivity.this).getString("userId");
        token = SharePreferencesHelper.getInstance(RegistrationInformationActivity.this).getString("token");
        Intent intent = getIntent();
        String startTime = intent.getStringExtra("startTime");
        String endTime = intent.getStringExtra("endTime");
        String address = intent.getStringExtra("address");
        String signPrice = intent.getStringExtra("signPrice");
        String title = intent.getStringExtra("title");
        showId = intent.getStringExtra("showId");
        String startDate = FormatCurrentData.getDate(startTime);
        String endDate = FormatCurrentData.getDate(endTime);
        time.setText(startDate + " 到 " + endDate);
        place.setText(address);
        if (signPrice.equals("0")) {
            cost.setText("免费");
        } else {
            cost.setText(signPrice);
        }
        competition_title.setText(title);
    }

    @Override
    protected void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.btn_confirm_enrollment:
                /*确认报名*/
                user = edit_competition_user.getText().toString();
                phone = edit_competition_phone.getText().toString();
                if (user.isEmpty()) {
                    toast(R.string.toast_name);
                } else if (TextUtils.isEmpty(phone)) {
                    toast(R.string.toast_phone);
                    return;
                } else if (!StringUtil.isPhoneNumber(phone)) {
                    toast(R.string.edit_need_phone_no);
                    return;
                } else {
                    SubmitInterface();
                }
                break;
            default:
                break;
        }
    }

    private void SubmitInterface() {
        ExhibitionRegistrationBean bean = new ExhibitionRegistrationBean();
        bean.setUserId(userID);
        bean.setToken(token);
        bean.setShowId(showId);
        bean.setSignName(user);
        bean.setSignPhone(phone);
        CommonInterface exhibitionRegistrationInterface = new CommonInterface(RegistrationInformationActivity.this, httpListener);
        exhibitionRegistrationInterface.getInterface("12005", JSON.toJSONString(bean));
    }

    private void showExhibitionDialog() {
        //当然是先初始化popupWindow
        final UtilPopupWindow popupWindow = new UtilPopupWindow();
        //我再工具中没有写构造函数，这里调用默认的构造函数
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        final int windowHeight = d.getHeight();
        //弹出框填充布局
        LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.popupwindow_sign_up_success, null);
        RelativeLayout layout2 = (RelativeLayout) getLayoutInflater().inflate(R.layout.activity_daily_exhibition, null);
        popupWindow.setPopupWindow(RegistrationInformationActivity.this, windowHeight, layout, layout2, Gravity.CENTER);
        ImageView view_order = (ImageView) layout.findViewById(R.id.view_order);
        view_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RegistrationInformationActivity.this, OrderInformationActivity.class);
                intent.putExtra("user", user);
                intent.putExtra("phone", phone);
                intent.putExtra("time", time.getText().toString());
                intent.putExtra("address", place.getText().toString());
                intent.putExtra("signPrice", cost.getText().toString());
                intent.putExtra("title", competition_title.getText().toString());
                intent.putExtra("showUserLogId", showUserLogId);
                startActivity(intent);
                popupWindow.dismiss();
            }
        });
        ImageView dimss_pupopwindow = (ImageView) layout.findViewById(R.id.dimss_pupopwindow);
        dimss_pupopwindow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                RegistrationInformationActivity.this.finish();
            }
        });

    }

    HttpListener httpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            showUserLogId = JsonUtil.getFieldValue(response, "showUserLogId");
            String isPay = JsonUtil.getFieldValue(response,"isPay");
            /*isPay": "报名是否需要支付[int]1：免费报名(直接跳报名成功接口) 2：需要支付（获取charge支付，接口12012）",*/
            if (errCode.equals("0000")) {

                if (isPay.equals("2")){
 /*获取ping++支付Charge*/
                    pingCharge();
                }else {
                    showExhibitionDialog();
                    IntegralChangeInterface.IntegralChange(RegistrationInformationActivity.this, userID, token, "8", "1", "报名成功");
                }

            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
        }
    };
    private void pingCharge() {
        OrderDetailsBean bean = new OrderDetailsBean();
        bean.setShowUserLogId(showUserLogId);
        bean.setToken(token);
        bean.setClientIp("0.0.0.0");
        bean.setPayType("1");
        CommonInterface commonInterface = new CommonInterface(RegistrationInformationActivity.this, pingHttpListener);
        commonInterface.getInterface("12012", JSON.toJSONString(bean));
    }
    HttpListener pingHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                String charge = JsonUtil.getFieldValue(response, "charge");
                id = JsonUtil.getFieldValue(charge, "id");
                //参数一：Activity 表示当前调起支付的Activity
                //参数二：data 表示获取到的charge或order的JSON字符串
                Pingpp.createPayment(RegistrationInformationActivity.this, charge);

            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
        }
    };
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //支付页面返回处理
        if (requestCode == Pingpp.REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getExtras().getString("pay_result");
            /* 处理返回值
             * "success" - 支付成功
             * "fail"    - 支付失败
             * "cancel"  - 取消支付
             * "invalid" - 支付插件未安装（一般是微信客户端未安装的情况）
             * "unknown" - app进程异常被杀死(一般是低内存状态下,app进程被杀死)
             */
                if (result.equals("success")) {
//                    status = "支付成功";
                    status = "1";
                    showExhibitionDialog();
                    IntegralChangeInterface.IntegralChange(RegistrationInformationActivity.this, userID, token, "8", "1", "报名成功");
                    pingChargeState();
                } else if (result.equals("fail")) {
//                    status = "支付失败";
                    status = "2";
                    ToastUtil.showToast("支付失败");
                    pingChargeState();
                } else if (result.equals("cancel")) {
                    ToastUtil.showToast("取消支付");
                    status = "2";
                    pingChargeState();
                } else if (result.equals("invalid")) {
                    ToastUtil.showToast("支付插件未安装");
                } else if (result.equals("unknown")) {
                    ToastUtil.showToast("app进程异常被杀死");
                }
                String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息

            }
        }
    }
    private void pingChargeState() {
        OrderDetailsBean bean = new OrderDetailsBean();
        bean.setShowUserLogId(showUserLogId);
        bean.setChargeId(id);
        bean.setPayType("1");
        bean.setStatus(status);
        bean.setToken(token);
        CommonInterface commonInterface = new CommonInterface(RegistrationInformationActivity.this, pingStatusHttpListener);
        commonInterface.getInterface("12013", JSON.toJSONString(bean));
    }
    HttpListener pingStatusHttpListener = new HttpListener(){
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
        }
    };

}